import * as XLSX from 'xlsx';
import * as fs from 'fs';
import * as path from 'path';
import { ExcelData, ParsedExcelFile } from './types';
// We are removing the dependency on applyParameterTableUpdates for this server-side parser.
// import { applyParameterTableUpdates } from './update-parameter-tables';

/**
 * [SERVER-SIDE ONLY]
 * Parses an Excel file from a file path.
 * This function is intended for use in Node.js environments.
 * @param filePath The absolute path to the Excel file.
 * @returns A ParsedExcelFile object.
 */
export function parseExcelFile_SERVER(filePath: string): ParsedExcelFile {
  const buffer = fs.readFileSync(filePath);
  const workbook = XLSX.read(buffer, { type: 'buffer' });
  const filename = path.basename(filePath);
  
  const sheets: ExcelData[] = workbook.SheetNames.map(sheetName => {
    const worksheet = workbook.Sheets[sheetName];
    const jsonData = XLSX.utils.sheet_to_json(worksheet, { 
      header: 1,
      defval: null,
      raw: false
    }) as (string | number | null)[][];
    
    const headers = jsonData[0] as string[] || [];
    const rows = jsonData.slice(1);
    
    const sheetData = {
      sheetName,
      headers: headers.map(h => h?.toString() || ''),
      rows
    };
    
    // Return the raw sheet data without applying any updates.
    return sheetData;
  });
  
  return { filename, sheets };
}

export function parseExcelBuffer(buffer: ArrayBuffer, filename: string): ParsedExcelFile {
  const workbook = XLSX.read(new Uint8Array(buffer), { type: 'array' });
  
  const sheets: ExcelData[] = workbook.SheetNames.map(sheetName => {
    const worksheet = workbook.Sheets[sheetName];
    const jsonData = XLSX.utils.sheet_to_json(worksheet, { 
      header: 1,
      defval: null,
      raw: false
    }) as (string | number | null)[][];
    
    const headers = jsonData[0] as string[] || [];
    const rows = jsonData.slice(1);
    
    const sheetData = {
      sheetName,
      headers: headers.map(h => h?.toString() || ''),
      rows
    };
    
    // In server context, we don't apply updates here
    return sheetData;
  });
  
  return {
    filename,
    sheets
  };
} 